package com.sntk.organauthomanager.infrastructure.dao;

import com.sntk.organauthomanager.domain.model.UserResource;
import com.sntk.organauthomanager.domain.model.UserResourceIdentify;
import com.sntk.organauthomanager.domain.repository.UserResourceRepository;
import com.sntk.organauthomanager.infrastructure.convert.UserResourceConvert;
import com.sntk.organauthomanager.infrastructure.db.entity.UserResourceEntity;
import com.sntk.organauthomanager.infrastructure.db.repository.UserResourceDBRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @ClassName: UserResourceRepositoryImpl
 * @author: wgchao
 * @createTime: 2020/9/16 9:37 AM
 * @Description: TODO
 */
@Component
public class UserResourceRepositoryImpl implements UserResourceRepository {
    @Autowired
    private UserResourceDBRepository userResourceDBRepository;
    @Autowired
    private UserResourceConvert userResourceConvert;

    @Override
    public void deleteAllOfUser(String uname, String operator) {
        userResourceDBRepository.deleteAllByUname(uname);
    }

    @Override
    public void add(UserResource userResource, String operator) {
        //删除原有关系
        userResourceDBRepository.deleteAllByUname(userResource.getIdentify().getUname());
        userResourceDBRepository.findAllByUname(userResource.getIdentify().getUname());


        List<UserResourceEntity> userResourceEntities = userResourceConvert.convert(userResource);
        if(userResourceEntities != null){
            userResourceEntities = userResourceEntities.stream().map(userResourceEntity -> {
                userResourceEntity.setCreateTime(new Date());
                userResourceEntity.setCreator(operator);
                return userResourceEntity;
            }).collect(Collectors.toList());
        }
        userResourceEntities = userResourceDBRepository.saveAll(userResourceEntities);
    }

    @Override
    public UserResource findByKey(UserResourceIdentify userResourceIdentify) {
        List<UserResourceEntity> userResourceEntities = userResourceDBRepository.
                findAllByUnameAndInstitutionNumber(userResourceIdentify.getUname(), userResourceIdentify.getInstitutionNumber());
        if(userResourceEntities==null || userResourceEntities.isEmpty()){
            return null;
        }
        return userResourceConvert.convert(userResourceEntities);
    }

    @Override
    public void delete(UserResourceIdentify userResourceIdentify, String operator) {
        userResourceDBRepository.deleteAllByUnameAndInstitutionNumber(userResourceIdentify.getUname(),
                userResourceIdentify.getInstitutionNumber());
    }

    @Override
    public void deleteAllOfUserNotInOrgan(String uname, List<String> organs, String operator) {
        userResourceDBRepository.deleteAllByUnameAndInstitutionNumberNotIn(uname, organs);
    }
}
